/**
 * Created by lixiaodi on 2019/06/06 0027.
 */
//模拟数据
mini.parse();
var grid = mini.get('datagrid1');					//收件箱列表
var searchForm = new mini.Form("searchFormBar");	//搜索栏目
var sendPeopleNameEl = mini.get('sendPeopleName');	//发件人元素
var pager = grid.getBottomPager();					//分页

var gridData = [];										//存放所有数据
var stateSql = '';										//查询信息列表(带状态)sql

//页面初始化
$(function(){
	stateSql = " and status = status";	//全部信息
	httpRequest('0',stateSql);
});
//表格的操作按钮绘制
function onActionRenderer(e) {
    var grid = e.sender;
    var record = e.record;
    var uid = record._uid;
    var rowIndex = e.rowIndex;
    var s = ' <a class="mini-button Edit_Button" href="javascript:onRead(\'' + uid + '\')" >查看</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onReply(\'' + uid + '\')" >回复</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onForward(\'' + uid + '\')" >转发</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onRemove(\'' + uid + '\')" >删除</a>';
    return s;
}
//选择发件人
function changePerson(){
	mini.open({
        url: bootPATH + "../frame/frame1/pages/booking/Mail/changePerson.html",
        title: "选择发件人",
        width: 600,
        height: 400,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                //赋值
                sendPeopleNameEl.setValue(data.operatorId);
                sendPeopleNameEl.setText(data.perName);
            }
        }
    });
}
//根据条件查询
function onSearch(){
	//得到查询条件数据
	searchData = searchForm.getData();
	//拼接查询sql
	var dataStr = stateSql;       //存放sql
	//通过name得到日期区间得元素并且得到用户填写得值
    var colum1 = mini.getByName('push_time').getValue();
    var colum2 = mini.getByName('push_time2').getValue();
    //如果值都不为空，那么执行sql语句
    if(colum1 != "" && colum2 != ""){
        if(tab(colum1,colum2)){
            colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
            colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
            dataStr += " and " + 'push_time' + " between '" + colum1 + "' and " + "'" + colum2 + "'";
        }else{
            mini.alert("第二个日期不能大于以一个日期");
        }
    }else if(colum1 == "" && colum2 != ""){
        colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " <= " + "'" + colum2 + "'";
    }else if(colum1 != "" && colum2 == ""){
        colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " >= " + "'" + colum1 + "'";
    }
    //删除时间字段
    delete searchData.push_time;
    delete searchData.push_time2;
    //除时间以外的sql拼接
    for(var key in searchData){
    	if(searchData[key]){
    		if(key == 'book_isbn'){
    			dataStr += " and "  + key + " in (" + searchData[key] + ")";
    		}else if(key == 'send_peopleName'){
    			dataStr += " and send_people like '%" + searchData[key] + "%'";
    		}else{
    			dataStr += " and "  + key + " like '%" + searchData[key] + "%'";
    		}
    	}
    }
    var searchSql = dataStr;
	//查询数据
	httpRequest('0',searchSql);
}
//已读list请求
function onAlreadyRead(){
	stateSql = " and status = 1";	//已读信息
	httpRequest('0',stateSql);
}
//未读list请求
function onUnread(){
	stateSql = " and status = 0";	//未读信息
	httpRequest('0',stateSql);
}
//全部list
function onAll(){
	httpRequest();
}
//查看详情
function onRead(row_uid){
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	if(row){
		//如果是已读状态就不请求改变状态
		if(row.status == '未读'){
			var msgObj = {
					entityName: 'MessageSend',
					msg_send_id: row.msg_send_id,
					msg_info_id: row.msg_info_id,
					msg_title: row.msg_title,
					msg_text: row.msg_text,
					appendix: '',
					send_people: row.send_people,	
					push_time: row.push_time,
					user_id: row.user_id,
					is_del: 0,
					status: '1',
					old_msg: row.old_msg
			};
			var msgStr = JSON.stringify(msgObj);
			//请求数据修改读取状态
			$.ajax({
	         	url: ajaxUrl + '/msg/openReciveMsg.do',
	             type: "post",
	             data: msgStr,
	             contentType : "application/json",
	             success: function (data) {
	            	//showTips(data.data);
	            	var seeMail = data.data;
	            	seeJump(row);
	             },
	             error: function () {
	                 mini.alert('失败');
	             }
	        });
		}else{
			seeJump(row);
		}
	}else{
		console.log('未选中行');
	}
}
//查看方法
function seeJump(row){
	//跳转查看页面
	row.types = 'inbox';
	localStorage.setItem('seeMailInfo',JSON.stringify(row));
	var item = {
        iconCls: "fa fa-desktop",
        text: "信息正文",
        url: "../pages/booking/Mail/msgInfo.html"
    };
    parent.activeTab(item);//与父页面通信
    //刷新list
 	httpRequest();
}
//回复
function onReply(row_uid){
	removeCache();
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	row.types = '回复';
	if(row){
		//将需要编辑的数据带过去
		localStorage.setItem("mailData",JSON.stringify(row));
		onJump('回复邮件');
	}
}
//转发
function onForward(row_uid){
	removeCache();
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	row.types = '转发';
	if(row){
		//将需要编辑的数据带过去
		localStorage.setItem("mailData",JSON.stringify(row));
		onJump('转发邮件');
	}
}
//删除(单条)
function onRemove(row_uid){
	//根据uid获取行数据(appendix:附件)
	var row = grid.getRowByUID(row_uid);
	var msgId = row.msg_send_id;
	mini.confirm('是否删除选中记录','系统提示',function (action){
		if(action == 'ok'){
			row.status = row.status == '未读' ? 0 : 1;
			var msgObj = {
					entityName: 'MessageSend',
					msg_send_id: row.msg_send_id,
					msg_info_id: row.msg_info_id,
					msg_text: row.msg_text,
					msg_title: row.msg_title,
					appendix: '',
					is_del: 1,
					old_msg: row.old_msg,
					push_time: row.push_time,
					status: row.status,
					user_id: row.user_id,
					send_people: row.send_peopleName,
					
			};
			var msgStr = JSON.stringify(msgObj);
			//请求数据修改读取状态
			$.ajax({
	         	url: ajaxUrl + '/msg/updateIsDel.do',
	             type: "post",
	             data: msgStr,
	             contentType : "application/json",
	             success: function (data) {
	            	if(data.status == 200){
	            		showTips2(data.data);
	            	}
	             	httpRequest();
	             },
	             error: function () {
	                 mini.alert('失败');
	             }
	        });
		}
	});
}
//批量删除
function onRemoves() {
    var rows = grid.getSelecteds();
    if (rows.length > 0) {
        mini.confirm("确定删除选中记录？","系统提示",function(action){
            if (action == "ok") {
                var ids = [];
                for (var i = 0, l = rows.length; i < l; i++) {
                    var r = rows[i];
                    ids.push(r.msg_send_id);
                }
                var id = ids.join(',');
                grid.loading("操作中，请稍后......");
                $.ajax({
                	url: ajaxUrl + '/msg/updateIsDels.do',
                    type: "post",
                    data: {
                    	ids: id
                    },
                    success: function (data) {
                    	grid.unmask();
                    	if(data.status == 200){
                    		showTips2(data.data);
                    		httpRequest();
                    	}else{
                    		mini.alert(data.data);
                    	}
                    },
                    error: function () {
                        mini.alert('失败');
                    }
                });
            }
        })
    }else {
        mini.alert("请选中一条记录");
    }
}
//彻底删除
function onDestroy(){
	 var rows = grid.getSelecteds();
	 if (rows.length > 0) {
		 mini.confirm("确定彻底删除选中记录？","系统提示",function(action){
			 if(action == "ok"){
				 var ids = [];
	             for (var i = 0, l = rows.length; i < l; i++) {
	            	 var r = rows[i];
	            	 ids.push(r.msg_send_id);
	             }
	             var id = ids.join(',');
	             grid.loading("操作中，请稍后......");
	             $.ajax({
	                    url: ajaxUrl + "/msg/delReciveMsg.do?ids=" + id,
	                    type:"post",
	                    success: function (data) {
	                    	grid.unmask();
	                        if(data.status == 200){
	                        	showTips2(data.data);
	                        	httpRequest();
	                        }else{
	                        	mini.alert(data.data);
	                        }
	                    },
	                    error: function () {
	                        mini.alert('失败');
	                    }
	                });  
			 }
		 });
	 } else {
		 mini.alert("请选中一条记录");
	 }
}
//清除缓存
function removeCache(){
	//查看是否有缓存，有的话清除缓存
	var cacheData = JSON.parse(localStorage.getItem('mailData'));
	//如果有缓存清楚缓存，关闭页面
	if(cacheData){
		localStorage.removeItem('mailData');
		//查看是否有回复页签打开，有的话关闭，打开新的
		var openTabsArr = parent.openTabs();
		openTabsArr.forEach(function (item,index){
			if(item.title == '回复邮件' || item.title == '转发邮件'){
				//关闭该页面
				parent.articleTab2(item);
			}
		});
	//如果没有缓存就是第一次打开
	}else{
		console.log('第一次打开');
	}
}
function httpRequest(pageIndex,paramSql){
	var pageObj = {
			pageSize: '500',
			pageNum: pageIndex,
			paramSql: paramSql
	}
	var pageStr = JSON.stringify(pageObj);
	grid.loading('请稍后...');
	$.ajax({
		url: ajaxUrl + '/msg/msgInList.do',
		type: 'POST',
		data: pageStr,
		contentType : "application/json",
		success: function(data){
			grid.unmask();
			if(data.status == 200){
				var mailList = data.data;
				mailList.forEach((item)=>{
					item.status = item.status ? '已读' : '未读';
					item.push_time = formatDateSec(item.push_time);
				});
				grid.setData(mailList);
				pager.set({"totalCount":data.count.count});        //设置分页总数
				gridData = mailList;
			}else if(data.status == 706){
				showTips('收件箱');
				grid.setData([]);
			}else{
				mini.alert(data.data);
			}
			
		},
		error: function(msg){
			console.log(msg);
			mini.alert('请求失败');
		}
	});
}
//跳转函数
function onJump(text){
	//跳转
	var item = {
		id: 'reply',
	    iconCls: "fa fa-desktop",
	    text: text,
	    url: "../pages/booking/Mail/mAddAndEdit.html"
	};
	//var data = parent.allTabs();
	parent.activeTab(item);//与父页面通信
}
//提示信息
function showTips2(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}